<?php


namespace models;


use think\Model;

class Article extends Model
{
    protected function special_equal($value){
        if(is_array($value)){
            foreach($value as $k=>$v){
                $value[$k]=$this->special_equal($v);
            }
        }else{
            $value=trim($value);
            if(strpos($value,'=') === 0){
                $value = "'".$value;
            }
        }
        return $value;
    }
    //导出
    //https://phpspreadsheet.readthedocs.io/en/latest/
    //https://www.jianshu.com/p/ed89c64fc630
    //https://blog.csdn.net/xcbzsy/article/details/132246402
    //https://blog.csdn.net/qq_34631220/article/details/132543643
    public function export($file_path, $data)
    {
        if (empty($data)) return true;

        if (!file_exists($file_path)) {
            @mkdir(dirname($file_path), 0777, true);
            $excel = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $excel->getActiveSheet();
            $sheet->setTitle('数据');
            foreach (range('A', 'Z') as $k => $v) {
                $sheet->getColumnDimension($v)->setWidth(20);
            }
            //var_dump(get_class_methods($sheet));

            $sheet->setCellValue('A1', 'ID');
            $sheet->setCellValue('B1', '标题');
            $sheet->setCellValue('C1', '添加人');

            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($excel, "Xlsx");
            $writer->save($file_path);

            $excel->disconnectWorksheets();
            unset($excel);
        }

        if (!file_exists($file_path)) {
            return false;
        }
        //向excel中追加数据
        $excel = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_path);
        $sheet = $excel->getActiveSheet();
        $rows = $sheet->getHighestRow();
        $row = $rows + 1;
        foreach ($data as $key => $value) {
            $value = $this->special_equal($value);

            $sheet->setCellValue("A{$row}", $value['itemid']);
            $sheet->setCellValue("B{$row}", $value['title']);
            $sheet->setCellValue("C{$row}", $value['username']);
            $row++;
        }
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($excel, "Xlsx");
        $writer->save($file_path);

        $excel->disconnectWorksheets();
        unset($excel);
        return true;
    }
}